<template>
  <div class="padding-tb" v-loading.fullscreen.lock="fullscreenLoading">
    <el-card>
      <div slot="header" class="flex align-center justify-between">
        <span class="title-icon">文件列表</span>
        <el-button-group class="">
          <el-button
            v-if="isAllocat"
            @click="isConfirmPredictionBtn"
            :type="btnColor"
            size="mini"
          >
            {{ isConfirmPredictionName }}
          </el-button>
          <el-button @click="lazyloadWaybillFile" type="primary" size="mini"
            >重新加载</el-button
          >

          <el-button
            @click="toUploadfile"
            v-if="verifyShow.uploadFile"
            type="primary"
            size="mini"
            >上传</el-button
          >

          <el-button @click="toSendEmailPage" type="primary" size="mini"
            >邮件</el-button
          >

          <el-button
            @click="batchDownLoadFile"
            v-if="verifyShow.downloadFile"
            type="primary"
            size="mini"
            >批量下载</el-button
          >

          <el-button @click="batchDeleteFile" type="primary" size="mini"
            >批量删除</el-button
          >
          <el-button
            @click="waybillFileTransferAgent"
            type="primary"
            size="mini"
            >推送文件至代理{{
              agentMap[Constatvariable["customsClearanceAgent"]]
            }}</el-button
          >
        </el-button-group>
      </div>
      <el-table size="mini" :data="fileList" @selection-change="selectL">
        <el-table-column
          type="selection"
          width="44"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          width="44"
          label="序号"
          align="center"
          prop="id"
        ></el-table-column>
        <el-table-column prop="fileTypeId" label="文件类型">
          <template slot-scope="scope">
            {{ fileTypeOptions[scope.row.fileTypeId] }}
          </template>
        </el-table-column>
        <el-table-column
          min-width="250"
          prop="fileName"
          label="文件名"
          show-overflow-tooltip
        ></el-table-column>

        <el-table-column min-width="80" prop="isPush" label="是否已推送">
          <template slot-scope="scope">
            {{ yesNo[scope.row.isPush] }}
          </template>
        </el-table-column>
        <el-table-column prop="automateSend" label="机器人是否发送">
          <template slot-scope="scope">
            {{ scope.row["automateSend"] ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="automateSendTime" label="机器人发送时间">
          <template slot-scope="scope">
            {{ scope.row["automateSendTime"] }}
          </template>
        </el-table-column>
        <el-table-column prop="cuser" label="创建人">
          <template slot-scope="scope">
            {{ userOptions[scope.row.cuser] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="cdate"
          label="创建时间"
          min-width="100"
        ></el-table-column>
        <el-table-column label="操作" min-width="200">
          <template slot-scope="scope">
            <!-- <i class="el-icon-edit pointer"></i> -->
            <!-- <el-tooltip content="编辑">
              <i
                style="color:blue;"
                class="el-icon-edit-outline text-xl margin-right-sm"
                @click="editFile(scope.$index, scope.row)"
              ></i>
            </el-tooltip> -->
            <el-tooltip content="预览">
              <i
                style="color:green;"
                class="el-icon-view text-xl margin-right-sm"
                @click="previewFile(scope.$index, scope.row)"
              ></i>
            </el-tooltip>
            <el-tooltip content="下载" v-if="verifyShow.downloadFile">
              <i
                style="color:#57dfecfa;"
                class="el-icon-download pointer margin-right-sm text-xl"
                @click="dowmLoadWaybillFile(scope.$index, scope.row)"
              ></i>
            </el-tooltip>
            <el-tooltip content="删除" v-if="verifyShow.deleteFile">
              <i
                style="color:red;"
                class="el-icon-delete pointer text-xl margin-right-sm"
                @click="deleteWaybillFile(scope.$index, scope.row)"
              ></i>
            </el-tooltip>
            <el-tooltip content="分配" v-if="isAllocat">
              <i
                class="el-icon-s-promotion text-xl margin-right-sm"
                @click="toAllocationFile(scope.$index, scope.row)"
              ></i>
            </el-tooltip>

            <el-tooltip v-if="isAllocat" effect="light" placement="left">
              <div slot="content">
                <el-table
                  v-if="sysncShow"
                  :data="fileData"
                  style="max-width:800px;overflow:auto;"
                >
                  <el-table-column
                    prop="waybillNo"
                    label="运单号"
                    width="100px;"
                  >
                  </el-table-column>
                  <el-table-column prop="inStockTotalPackages" label="件数">
                  </el-table-column>
                  <el-table-column
                    prop="inStockChannel"
                    label="渠道"
                    width="200px;"
                  >
                  </el-table-column>
                  <el-table-column prop="creator" label="创建人" width="100px;">
                  </el-table-column>
                  <el-table-column
                    prop="createTime"
                    label="创建时间"
                    width="100px;"
                  >
                  </el-table-column>
                  <el-table-column prop="remark" label="备注" width="100px;">
                  </el-table-column>
                </el-table>
                <span>
                  点击查看
                </span>
              </div>
              <i
                class="el-icon-s-fold text-xl"
                @click="
                  synchronizedLoadAllocatedWayBillfile(scope.$index, scope.row)
                "
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          min-width="200"
          prop="remark"
          label="备注"
        ></el-table-column>
      </el-table>
    </el-card>
    <Uploadfile
      ref="Uploadfile"
      :fileTypeOptions="fileTypeOptions"
      :data="Constatvariable"
    ></Uploadfile>
    <SendEmailPage
      ref="SendEmailPage"
      :userOptions="userOptions"
      :data="Constatvariable"
    ></SendEmailPage>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
const Uploadfile = () => import("./Uploadfile");
const SendEmailPage = () => import("./SendEmailPage");
import { m } from "@/store/yg/common/local";

export default {
  components: {
    Uploadfile,
    SendEmailPage
  },
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    isAllocat: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      agentMap: {},
      fullscreenLoading: false,
      btnColor:
        1 == this.Constatvariable.isConfirmPrediction ? "success" : "danger",
      isConfirmPredictionName:
        1 == this.Constatvariable.isConfirmPrediction
          ? "取消已放预报"
          : "确认已放预报",
      yesNo: {
        1: "是",
        0: "否"
      },
      sysncShow: false,

      fileData: [],
      fileList: [],
      userOptions: {},
      fileTypeOptions: {},
      listSelect: [],
      listSelectId: [],
      waybillId: ""
    };
  },
  mounted() {
    this.fetchAgentApi();
  },
  methods: {
    // 初始化 下载
    fetchAgentApi() {
      var param = {};
      var key = "agent_api_init";
      var agents = JSON.parse(sessionStorage.getItem(key));

      if (!agents || agents == "{}" || agents == null || agents == "null") {
        ajax("fetchAgentApi", param).then(
          res => {
            if (res.code == 200) {
              this.agentMap = res.data;
              sessionStorage.setItem(key, JSON.stringify(this.agentMap));
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.agentMap = agents;
      }
    },

    editFile(index, row) {
      this.$refs.Uploadfile.centerDialogVisible = true;
      this.$refs.Uploadfile.queryParams = row;
    },
    previewFile(index, row) {
      console.log(row);
      var param = {};

      var fileName = row.fileUrl;
      param["fileName"] = fileName;
      var name = row.fileName;
      var uploadpath = "/";
      console.log(fileName);
      var path = (path = constant.FILE_SERVER + uploadpath);
      var fileUrl = path + fileName;
      // var url = "/#/view/viewWaybillFile?fileUrl=" + fileUrl;
      var fileExt = /[.]/.exec(fileName)
        ? /[^.]+$/.exec(fileName.toLowerCase())
        : ""; // 文件扩展名
      console.log("names", fileExt);
      if (
        fileExt == "pdf" ||
        fileExt == "jpg" ||
        fileExt == "tif" ||
        fileExt == "bmp" ||
        fileExt == "gif" ||
        fileExt == "png" ||
        fileExt == "jpeg"
      ) {
        window.open(fileUrl, "_blank");
      } else if (
        fileExt == "doc" ||
        fileExt == "docx" ||
        fileExt == "xlsx" ||
        fileExt == "xls" ||
        fileExt == "pptx" ||
        fileExt == "ppt"
      ) {
        ajax("filePreviewByServer", param).then(
          res => {
            if (res.code != 200) {
            } else {
              window.open(res.data);
            }
          },
          error => {
            console.log(error);
          }
        );
      }
    },
    isConfirmPredictionBtn() {
      var confirmPrediction = "是否确认已放预报？";
      if (1 == this.Constatvariable.isConfirmPrediction) {
        confirmPrediction = "是否取消已放预报？";
      }
      this.$confirm(confirmPrediction).then(_ => {
        if (1 == this.Constatvariable.isConfirmPrediction) {
          this.btnColor = "danger";
        } else {
          this.btnColor = "success";
        }
        var param = {};
        param["id"] = this.Constatvariable.id;
        param["param5"] = this.Constatvariable.isConfirmPrediction;
        this.fullscreenLoading = true;
        ajax("isConfirmPrediction", param).then(
          res => {
            this.fullscreenLoading = false;
            if (res.code != 200) {
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("修改失败!");
              }
            } else {
              this.$message.success("修改成功!");
              if (1 == this.Constatvariable["isConfirmPrediction"]) {
                this.isConfirmPredictionName = "确认已放预报";
                this.Constatvariable.isConfirmPrediction == 0;
                this.btnColor = "danger";
              } else {
                this.isConfirmPredictionName = "取消已放预报";
                this.Constatvariable.isConfirmPrediction == 1;
                this.btnColor = "success";
              }
            }
          },
          error => {
            console.log(error);
          }
        );
      });
    },

    selectL(selection, row) {
      this.listSelect = selection;
      this.listSelectId = selection.map(item => item.id);
    },
    //上传文件
    toUploadfile() {
      this.$refs.Uploadfile.centerDialogVisible = true;
      this.$refs.Uploadfile.queryParams = {};
    },

    synchronizedLoadAllocatedWayBillfile(index, row) {
      console.log(row);
      var fileUrl = row.fileUrl;
      var param = {};

      param["waybillFileId"] = row.id;
      param["waybillId"] = this.Constatvariable.id;
      param["shippingWay"] = this.Constatvariable.shippingWay;
      this.fullscreenLoading = true;
      ajax("synchronizedLoadAllocatedWayBillfile", param).then(
        res => {
          this.fullscreenLoading = false;
          this.sysncShow = true;
          if (res.code != 200) {
          } else {
            this.fileData = res.data;
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    toAllocationFile(index, row) {
      //获取当前路由地址

      var url = "#/blank/waybill__allocationtraceFile__main";
      // this.$nextTick(()=>{
      // this.$store.dispatch("loadBlankEntry", url);
      url =
        url +
        "?fileId=" +
        row.id +
        "&waybillId=" +
        this.Constatvariable.id +
        "&fileName=" +
        row.fileName;
      window.open(url, "_blank");
    },
    /** 直接通过保存到数据库的地址下载文件*/
    dowmLoadWaybillFile(index, row) {
      var fileName = row.fileUrl;
      var name = this.codeEfilter(row.fileName);
      var uploadpath = "/";
      console.log(fileName);
      var path = (path = constant.FILE_SERVER + uploadpath);
      var fileUrl = path + fileName;
      console.log(name);
      location.href =
        constant.API_SERVER +
        "/open/downloadFileByHttp?path=" +
        fileUrl +
        "&fileName=" +
        name;
    },
    codeEfilter(value) {
      value = encodeURIComponent(value);
      // .replace("#", "%23")
      // .replace("%", "%25")
      // .replace("&", "%26")
      // .replace("+", "%2B")
      // .replace("//", "%2F")
      // .replace("=", "%3D")
      // .replace("!", "%21")
      // .replace("*", "%2A")
      // .replace('"', "%22")
      // .replace("'", "%27")
      // .replace("(", "%28")
      // .replace(")", "%29")
      // .replace(";", "%3B")
      // .replace(":", "%3A")
      // .replace("@", "%40")
      // .replace("$", "%24")
      // .replace(",", "%2C")
      // .replace("/\[/g", "%5B")
      // .replace("/\]/g", "%3B")
      // .replace("?", "%3F");

      return value;
    },

    deleteWaybillFile(index, row) {
      this.$confirm("是否确认删除文件？")
        .then(_ => {
          console.log(row);
          var fileUrl = row.fileUrl;
          var param = {};
          param["id"] = row.id;
          param["fileUrl"] = fileUrl;
          this.fullscreenLoading = true;
          ajax("deleteWaybillFile", param).then(
            res => {
              this.fullscreenLoading = false;
              if (res.code != 200) {
                if (null != res.message) {
                  this.$message.error(m(res.message));
                } else {
                  this.$message.error("修改失败!");
                }
              } else {
                this.$message.success("删除成功!");
                this.fileList.splice(index, 1);
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    },

    waybillFileTransferAgent() {
      if (!this.listSelect.length > 0) {
        this.$message.error("请选择文件！");
        return;
      }
      var param = {};

      param["id"] = this.Constatvariable["customsClearanceAgent"];
      param["ids"] = this.listSelectId;
      param["waybillId"] = this.Constatvariable.id;
      this.fullscreenLoading = true;
      ajax("waybillFileTransferAgent", param).then(
        res => {
          this.fullscreenLoading = false;
          if (res.code == 200) {
            // 初始化
            this.$message.success("推送成功!");
          } else {
            if (null != res.message) {
              this.$message.error("推送失败原因：" + res.message);
            } else {
              this.$message.error("推送失败!");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    // 批量删除文件
    batchDeleteFile() {
      if (!this.listSelect.length > 0) {
        this.$message.error("请选择文件！");
        return;
      }
      this.$confirm("是否确认删除选中文件？")
        .then(_ => {
          this.listSelect.forEach(element => {
            var fileUrl = element.fileUrl;
            var param = {};
            param["id"] = element.id;
            param["fileUrl"] = fileUrl;
            this.fullscreenLoading = true;
            ajax("deleteWaybillFile", param).then(
              res => {
                this.fullscreenLoading = false;
                if (res.code != 200) {
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("修改失败!");
                  }
                } else {
                  this.$message.success("删除成功!");
                  this.lazyloadWaybillFile();
                  this.fileList.splice(index, 1);
                  // location.reload();
                }
              },
              error => {
                console.log(error);
              }
            );
          });
        })
        .catch(_ => {});
    },
    batchDownLoadFile() {
      if (!this.listSelect.length > 0) {
        this.$message.error("请选择文件！");
        return;
      }
      var postUrl = "batchExportWaybillFileByWaybillIds";
      var param = {};
      param["ids"] = this.listSelectId;
      param["param1"] = "文件批量下载";
      ajax(postUrl, param).then(
        res => {
          console.log(res);
          this.fullscreenLoading = false;
          if (res.errorMesage) {
            this.$message.error(m(res.errorMesage));
          } else {
            var path = (path = constant.FILE_SERVER + res.path);
            var fileUrl = path;
            console.log(fileUrl);
            window.open(fileUrl);

            // location.href =
            //   constant.API_SERVER +
            //   "/open/downloadFileByHttp?fileName=" +
            //   res.fileName +
            //   "&path=" +
            //   path;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    toSendEmailPage() {
      if (!this.listSelect.length > 0) {
        this.$message.error("请选择文件！");
        return;
      }
      this.copyTotemp();
      this.fullscreenLoading = true;
      var param = {};

      param["waybillId"] = this.Constatvariable.id;
      ajax("toSendEmailPage", param).then(
        res => {
          this.fullscreenLoading = false;
          if (res.code == 200) {
            // 初始化
            this.$refs.SendEmailPage.packetData.contentFile = [];
            this.listSelect.forEach(element => {
              this.$refs.SendEmailPage.packetData.contentFile.push(
                element.fileName
              );
            });
            this.$refs.SendEmailPage.centerDialogVisible = true;
            this.$refs.SendEmailPage.fileList = this.listSelect;
            this.$refs.SendEmailPage.packetData.subject =
              res.data["defaultSubject"];
            this.$refs.SendEmailPage.packetData.content =
              res.data["defaultContent"];
            this.$refs.SendEmailPage.packetData.sendIno = res.data["userId"];
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    copyTotemp() {
      var param = {};
      var ids = [];
      this.listSelect.forEach(element => {
        ids.push(element.id);
      });
      param["ids"] = ids;

      ajax("copyWaybillFileToTmp", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            }
          } else {
            console.log("复制附件成功");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    lazyloadWaybillFile() {
      var param = {};
      var waybillId = this.Constatvariable.id;
      if (!waybillId) {
        waybillId = this.$route.query.waybillId;
      }
      console.log("waybillId === " + waybillId);
      param["id"] = waybillId;
      this.fullscreenLoading = true;
      ajax("lazyloadWaybillFile", param).then(
        res => {
          this.fullscreenLoading = false;
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            }
          } else {
            this.userOptions = res.data["userMap"];
            this.fileTypeOptions = res.data["fileTypeMap"];
            sessionStorage.setItem(
              "fileTypeMap",
              JSON.stringify(this.fileTypeOptions)
            );
            this.fileList = res.data["waybillFiles"];
          }
        },
        error => {
          console.log(error);
        }
      );
    }
  },
  mounted() {
    this.lazyloadWaybillFile();
  }
};
</script>

<style></style>
